package com.mingtu.guards.fragment;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.GridSpacingItemDecoration2;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.ContainsEmojiEditText;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.activity.AnimalDetailsActivity;
import com.mingtu.guards.adapter.BioAdapter;
import com.mingtu.guards.bean.AnimalResourceBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;
import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class BioFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {

    @BindView(R.id.edit_search)
    ContainsEmojiEditText editSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    private SmartRefreshLayout srlUp;

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private String genus = null;
    private String classType = null;
    private String kmName = null;
    private String keyword = null;
    private String levelName = null;
    private BioAdapter bioAdapter;

    public static BioFragment getInstance() {
        BioFragment fragment = new BioFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_bio;
    }

    @Override
    protected void initData() {

        bioAdapter = new BioAdapter(context);
        GridLayoutManager layoutManager = new GridLayoutManager(context, 2);//第二个参数为网格的列数
        recycler.addItemDecoration(new GridSpacingItemDecoration2(2, SizeUtils.dp2px(ItemDecorationSpaces), false, 0));
//        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(layoutManager);

        if (isOpenLoadAnimation) {
            bioAdapter.isFirstOnly(isFirstOnly);
            bioAdapter.openLoadAnimation(animationType);
        }

        bioAdapter.setEmptyView(new EmptyDataLayout(context));
        View footerView = View.inflate(getActivity(), R.layout.layout_bio_bottom_place, null);
        bioAdapter.addFooterView(footerView);

        recycler.setAdapter(bioAdapter);
        bioAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AnimalResourceBean.PageBean.ListBean listBean = bioAdapter.getData().get(position);
                String resId = listBean.getId() + "";
                String name = listBean.getName();
                if (!StringUtils.isEmpty(resId)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("resId", resId);
                    bundle.putString("name", name);
                    IntentUtils.getInstance().readyGo(getActivity(), AnimalDetailsActivity.class, bundle);
                } else {
                    ToastUtils.showLong(getResources().getString(R.string.data_error));
                }
            }
        });
        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    //此处做逻辑处理
                    keyword = UIUtils.getTextView(textView);
                    classType = null;
                    genus = null;
                    levelName = null;
                    kmName = null;
                    getResList(1);

                    return true;
                }
                return false;
            }
        });


    }

    @Override
    protected void initView(View view) {
        srlUp = (SmartRefreshLayout) view.findViewById(R.id.srl_up);
    }

    @Override
    protected void getData() {
        initListener();
        getResList(1);
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getResList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(bioAdapter.getData(), Constant.PAGE_SIZE);
                    getResList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 动物资源列表
     *
     * @param pageNum
     */
    private void getResList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("keyword", keyword);
        hashMap.put("type", classType);
        hashMap.put("level", levelName);
        hashMap.put("familyName", kmName);
        hashMap.put("genus", genus);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_RES_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            AnimalResourceBean animalResourceBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                animalResourceBean = new AnimalResourceBean();
                                animalResourceBean = gson.fromJson(result, AnimalResourceBean.class);
                                List<AnimalResourceBean.PageBean.ListBean> dataBeans = animalResourceBean.getPage().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            bioAdapter.replaceData(dataBeans);
                                        } else {
                                            bioAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }


                        }
                    }
                });
    }

    /**
     * 刷新列表
     */
    public void refresh(String kmName, String genus, String levelName, String classType) {
        this.kmName = kmName;
        this.genus = genus;
        this.levelName = levelName;
        this.classType = classType;
        getResList(1);
    }


    /**
     * 重置数据
     *
     * @param kmName
     * @param genus
     * @param levelName
     * @param classType
     */
    public void reset(String kmName, String genus, String levelName, String classType) {
        this.kmName = kmName;
        this.genus = genus;
        this.levelName = levelName;
        this.classType = classType;
        this.keyword = null;
        editSearch.setText("");
        getResList(1);
    }


    @OnClick(R.id.tv_search)
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                keyword = UIUtils.getEditText(editSearch);
                classType = null;
                genus = null;
                levelName = null;
                kmName = null;
                getResList(1);
                break;
        }
    }
}